package com.axend.aerosense.home.viewmodel;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseDevInfoBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.home.R;
import com.axend.aerosense.home.entity.HomeBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.ToastUtils;

import io.reactivex.disposables.Disposable;

public class HomeViewModel extends CustomBaseViewModel<HomeBean>  {
    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;
    private Disposable disposable;

    public HomeViewModel(IBaseView baseViewImpl, ILoadDataResult<HomeBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        ARouter.getInstance().inject(this);
    }

    @Override
    public void onLoad() {
        disposable = EasyHttp.post(UrlApi.URL.UserHome.getUrl())
                .headers("token", iLoginService.getToken())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<HomeBean>() {
                    @Override
                    public void onTokenExpire() {
                        loadDataFail("");
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(HomeBean bean) {
                        loadDataSuccess(bean);
                        // 下次加载数据认为是刷新
                        isRefresh = true;
                    }
                });

    }

    @Override
    protected void onCleared() {
        if (null != disposable && !disposable.isDisposed()){
            disposable.dispose();
        }
        super.onCleared();
    }
}
